# streamlink --http-proxy “http://127.0.0.1:1080”  --hls-live-restart --loglevel trace -o "test.ts" "https://www.youtube.com/watch?v=V9BZIj6bkuM" "best"
# ffmpeg -i xxx.ts -codec copy xxx.mp4

import os
import requests
import youtube_dl

from utils.erro import FFmpegError, StreamLinkDownloadError

from PIL import Image


def graph(tid, use_proxy: bool):
    proxies = {
        'http': '127.0.0.1:1080',
        'https': '127.0.0.1:1080'
    } if use_proxy else None

    path = os.path.join(os.path.abspath('.'), str(tid))

    f = open(f'{path}/info.txt', 'r', encoding='utf8')

    f.readline()
    f.readline()
    graphUrl = f.readline().rstrip()

    graphPath = f'{path}/graph.jpg'
    r = requests.get(graphUrl, proxies=proxies)
    if r.status_code == 200:
        with open(graphPath, 'wb') as gf:
            gf.write(r.content)
    else:
        raise IOError()

    im = Image.open(graphPath)
    out = im.resize((1146, 717), Image.ANTIALIAS)
    out.save(graphPath)
    f.close()


def split_video(path):
    file_size = os.path.getsize(f'{path}/video.mp4')
    # 8G 大小
    maxsize = 8589934592
    vlist = []
    if file_size < maxsize:
        vlist.append(f"{path}/video.mp4")
    else:
        file_num = int(file_size / maxsize) + 1
        for i in range(1, file_num + 1):
            startHour = (i - 1) * 5
            endHour = i * 5
            if i != file_num:
                return_code = os.system(
                    f"ffmpeg -ss {startHour}:00:00  -i {path}/video.mp4 -codec copy -t {endHour}:00:00 {path}/out{i}.mp4")
            else:
                return_code = os.system(
                    f"ffmpeg -ss {startHour}:00:00  -i {path}/video.mp4 -codec copy  {path}/out{i}.mp4")
            if return_code != 0:
                raise FFmpegError()
            vlist.append(f"{path}/out{i}.mp4")
    return vlist


def stream(tid, use_proxy: bool):
    path = os.path.join(os.path.abspath('.'), str(tid))

    f = open(f'{path}/info.txt', 'r', encoding='utf8')
    f.readline()
    vid = f.readline().rstrip()
    proxy_str = '--http-proxy "http://127.0.0.1:1080"' if use_proxy else ""
    stream_command = f'python -m streamlink {proxy_str} --hls-live-restart --loglevel trace ' \
                     f'-o "{path}/video.ts" "https://www.youtube.com/watch?v={vid}" "720p"'

    os.system(stream_command)

    # if return_code != 0:
    #     raise StreamLinkDownloadError()
    return_code = os.system(f"ffmpeg -i {path}/video.ts -codec copy {path}/video.mp4")
    if return_code != 0:
        raise FFmpegError()

    f.close()

    return split_video(path)

"""
def video_rec(tid, use_proxy: bool):
    path = os.path.join(os.path.abspath('.'), str(tid))

    f = open(f'{path}/info.txt', 'r', encoding='utf8')
    f.readline()
    vid = f.readline().rstrip()

    ydl_opts = {
        'proxy': 'socks5://127.0.0.1:1080'if use_proxy else None,
        'simulate': True,
        'quiet': True,
    }

    ydl = youtube_dl.YoutubeDL(ydl_opts)


    f.close()

    return split_video(path)

"""

if __name__ == '__main__':
    task_id = 1612101763047323000
    path = os.path.join(os.path.abspath('.'), str(task_id))
    print(split_video(path))
    # path = os.path.join(os.path.abspath('.'), str(task_id))
    # return_code = os.system(f"ffmpeg -i {path}/video.ts -codec copy {path}/video.mp4")
    # print(return_code)
    # graph(task_id)
    # stream(task_id)
